package com.customization.unionpay.market.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.service.ClearingRefundService;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.CloudFlashPaymentUtils;
import com.customization.unionpay.market.util.PropUtils;
import com.engine.core.impl.Service;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class ClearingRefundServiceImpl extends Service implements ClearingRefundService {

    private static final Logger log = LoggerFactory.getLogger(ClearingRefundServiceImpl.class);

    @Override
    public synchronized JSONObject clearRefundCreateWorkFlow(String serialCode, String applicant, String actAuthCode, String balanceAmount, String fileUrl, String consistentFundVft,  String accountIsUnique,String mIsSame,String fundIncomeIsSame,String fundIncomeConfigIsSame,String investmentAmountIsSame,String source) throws Exception {
        try {
            // 清算退款清算流程id
            String workId = PropUtils.BB_LOG.getPropValue("marketSubject", "clear_activity_work_id");
            String isNext = "0";


            // 流水号  serial_code
            // 申请人（工号或其他唯一标识） applicant
            // 营销平台活动授权码 actAuthCode
            // 结余金额 balance_amount
            // 附件 file_url
            // 资金核对一致  consistent_fund_vft
            // 打款账户唯一  account_is_unique
            // m1=m2       m_is_same
            // 资金收付是否一致                fund_income_is_same
            // 资金收入（配置）是否一致          fund_income_config_is_same
            // 出资金额与流水金额一致           investment_amount_is_same

            JSONObject json  = new JSONObject();

            // 申请人转换
            String idByResourceCode = com.customization.unionpay.market.util.FormDataUtils.getIdByResourceLoginId(applicant);

            User userApp = User.getUser(Util.getIntValue(idByResourceCode), 0);
            log.info("userApp:" + userApp);

            JSONObject sqr  = new JSONObject();
            sqr.put("name","sqr");
            sqr.put("type","");
            sqr.put("value",idByResourceCode);
            json.put("sqr",sqr);

            JSONObject lyxt  = new JSONObject();
            lyxt.put("name","lyxt");
            lyxt.put("type","");
            lyxt.put("value",source);
            json.put("lyxt",lyxt);

            // 营销平台活动授权码
            JSONObject yxpthdsqm  = new JSONObject();
            yxpthdsqm.put("name","yxpthdsqm");
            yxpthdsqm.put("type","");
            yxpthdsqm.put("value",actAuthCode);
            json.put("yxpthdsqm",yxpthdsqm);

            List<String> list = new ArrayList<>();
            list.add(actAuthCode);

            // TODO 对接云闪付
            String resultStr = CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(list);
            log.info("返回参数：" + resultStr);

            JSONObject resultJson = JSONObject.parseObject(resultStr);

            String errorMessage = resultJson.getString("errorMessage");
            if ("成功".equals(errorMessage)) {
                JSONArray data = resultJson.getJSONArray("data");
                log.info("解析data参数：" + data);
                if(data.size() > 0) {
                    JSONObject single = data.getJSONObject(0);
                    // 项目名称
                    String projectName = single.getString("projectName");
                    // 业务类型
                    String projectBusiType = single.getString("projectBusiType");
                    log.info("云闪付活动类型：" + projectBusiType);
                    String projectBusiTypeByTypeValue = getProjectBusiTypeByTypeValue(projectBusiType);

                    if (StrUtil.isNotBlank(projectBusiTypeByTypeValue)) {
                        // 活动类型
                        JSONObject actTp = new JSONObject();
                        actTp.put("name", "ACT_TP");
                        actTp.put("type", "");
                        actTp.put("value", projectBusiTypeByTypeValue);
                        json.put("ACT_TP", actTp);

                        // 活动名称

                        JSONObject ACT_NM = new JSONObject();
                        ACT_NM.put("name", "ACT_NM");
                        ACT_NM.put("type", "");
                        ACT_NM.put("value", projectName);
                        json.put("ACT_NM", ACT_NM);

                        log.info("fileUrl：" + fileUrl);
                        // 附件上传 TODO 需要确认
                        if(fileUrl != null && !"".equals(fileUrl)) {
                            JSONObject fjsc = new JSONObject();

                            List<JSONObject> fjscFieldValues = new ArrayList<>();

                            String[] fUs = fileUrl.split(",");
                            for (String furl : fUs) {
                                JSONObject fjscFieldValue = new JSONObject();
                                fjscFieldValue.put("value", furl);
                                String title = com.customization.unionpay.market.util.FormDataUtils.getPreTitle(furl);
                                String tail = com.customization.unionpay.market.util.FormDataUtils.getTailTitle(furl);
                                fjscFieldValue.put("type", title + ":" + tail);
                                fjscFieldValues.add(fjscFieldValue);
                            }

                            fjsc.put("name", "fjsc");
                            fjsc.put("type", "file");
                            fjsc.put("value", fjscFieldValues);
                            json.put("fjsc", fjsc);
                        }

                        // 资金核对一致
                        JSONObject zjhdyz = new JSONObject();
                        zjhdyz.put("name", "zjhdyz");
                        zjhdyz.put("type", "");
                        zjhdyz.put("value", consistentFundVft);
                        json.put("zjhdyz", zjhdyz);

                        // 打款账户唯一
                        JSONObject dkzhwy = new JSONObject();
                        dkzhwy.put("name", "dkzhwy");
                        dkzhwy.put("type", "");
                        dkzhwy.put("value", accountIsUnique);
                        json.put("dkzhwy", dkzhwy);

                        // m1=m2
                        JSONObject m1m2 = new JSONObject();
                        m1m2.put("name", "m1m2");
                        m1m2.put("type", "");
                        m1m2.put("value", mIsSame);
                        json.put("m1m2", m1m2);

                        // 资金收付是否一致
                        JSONObject zjsfsfyz = new JSONObject();
                        zjsfsfyz.put("name", "zjsfsfyz");
                        zjsfsfyz.put("type", "");
                        zjsfsfyz.put("value", fundIncomeIsSame);
                        json.put("zjsfsfyz", zjsfsfyz);

                        // 资金收入（配置）是否一致
                        JSONObject zjsrpzsfyz = new JSONObject();
                        zjsrpzsfyz.put("name", "zjsrpzsfyz");
                        zjsrpzsfyz.put("type", "");
                        zjsrpzsfyz.put("value", fundIncomeConfigIsSame);
                        json.put("zjsrpzsfyz", zjsrpzsfyz);

                        // 出资金额与流水金额一致
                        JSONObject czjeylsjeyz = new JSONObject();
                        czjeylsjeyz.put("name", "czjeylsjeyz");
                        czjeylsjeyz.put("type", "");
                        czjeylsjeyz.put("value", investmentAmountIsSame);
                        json.put("czjeylsjeyz", czjeylsjeyz);

                        List<JSONObject> sonData = new ArrayList<>();

                        JSONObject singleSonData = new JSONObject();
                        // 结余金额
                        JSONObject jyje = new JSONObject();
                        // 万元转元
                        String changeWanYuanToYuan = com.customization.unionpay.market.util.FormDataUtils.changeWanYuanToYuan(balanceAmount);
                        log.info("结余金额:" + changeWanYuanToYuan);
                        jyje.put("name", "jyje");
                        jyje.put("type", "");
                        jyje.put("value", changeWanYuanToYuan);
                        singleSonData.put("jyje", jyje);

                        // 可退款金额 = 结余金额 - 累计退款金额
                        Double refundAmount = refundAmountByAuthCode(actAuthCode);
                        if (refundAmount != null) {
                            Double balanceAmountDb = Double.parseDouble(changeWanYuanToYuan);

                            JSONObject ktkje = new JSONObject();
                            ktkje.put("name", "ktkje");
                            ktkje.put("type", "");
                            ktkje.put("value", balanceAmountDb - refundAmount);
                            singleSonData.put("ktkje", ktkje);
                            sonData.add(singleSonData);

                            json.put("sonData", sonData);

                            // 主表字段长度
                            int size = json.size() - 1;

                            String requestid = com.customization.unionpay.market.util.FormDataUtils.createWorkFlow(userApp, json, size, sonData.size(), workId, isNext, "0", "营销项目管理平台营销退款-"+actAuthCode);

                            JSONObject result = new JSONObject();
                            result.put("requestid", requestid);
                            return result;
                        } else {
                            throw new Exception("获取累计退款金额异常！");
                        }
                    } else {
                        throw new Exception("请求异常：当前云闪付业务类型枚举类型不匹配！");
                    }
                }else {
                    throw new Exception("云闪付根据授权码查询为空！");
                }
            } else {
                throw new Exception("请求异常：" + resultJson.getString("errorCode") + "----" + resultJson.getString("errorMessage"));
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 根据授权码获取累计退款金额 TODO 缺字段
     * @param authCode
     * @return
     */
    private Double refundAmountByAuthCode(String authCode){
        RecordSet rs = new RecordSet();
        try {
            // 营销退款明细台账表单id
            int refundDetailsFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_refund_details_form_id"));

            String shtg = com.customization.unionpay.market.util.FormDataUtils.getItemValue(refundDetailsFormId, "tksqdzt", "审批通过");
            log.info("审批通过："+shtg);
            if (StrUtil.isNotBlank(shtg)) {
                // 获取营销退款明细台账主表表名
                String refundDetailsTableName = FormDataUtils.getTableName(refundDetailsFormId);
                log.info("获取营销退款明细台账主表表名："+refundDetailsTableName);
                if(StrUtil.isNotBlank(refundDetailsTableName)){
                    // 累加金额 （本次申请退款金额）
                    String sql = "select sum(bcsqtkje) as hjje from #{tableName} where 1=1 and tksqdzt=? and yxpthdsqm=? ";

                    sql = sql.replace("#{tableName}",refundDetailsTableName);
                    log.info("sql:"+sql);

                    rs.executeQuery(sql,shtg,authCode);
                    if (rs.next()) {
                        return rs.getDouble("hjje");
                    }
                }else {
                    log.error("查询获取营销退款明细台账主表表名异常!");
                }
            }
        }catch (Exception e){
            log.error("查询异常："+e.getMessage());
        }
        return null;
    }

    /**
     * 根据云闪付值获取
     * @param projectBusiType
     * @return
     */
    public String getProjectBusiTypeByTypeValue(String projectBusiType){
        if("0".equals(projectBusiType)){
            // 立减活动 -- 立减
            return projectBusiType;
        }else if("1".equals(projectBusiType)) {
            // 积分（普通） -- 积分（普通）
            return projectBusiType;
        }else if("2".equals(projectBusiType)) {
            // 消费送红包 -- 积分（消费送红包）
            return "3";
        }else if("3".equals(projectBusiType)) {
            // 激励金 -- 奖励金
            return "2";
        }else {
            // 4  新积分（补贴） 99 其他
            return null;
        }
    }
}
